package com.jj.util.http;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.*;
import java.util.Enumeration;
import java.util.Map;
import java.util.Map.Entry;

public class HttpUtil {
	private static final Logger log = LoggerFactory.getLogger(HttpUtil.class);

	public static String getURL(String s) throws UnsupportedEncodingException,
			IOException {
		return getURL(s, "GBK");
	}

	public static String getURL(String s, String code)
			throws UnsupportedEncodingException, IOException {
		if (code.equals("")) {
			code = "GBK";
		}
		BufferedReader br = null;
		String data = "";
		log.info("get url : {}, code is:{}", new Object[] { s, code });
		URL url = new URL(s);
		
		HttpURLConnection urlCon = (HttpURLConnection)url.openConnection();
		urlCon.setConnectTimeout(10000);	// 连接超时时间
		urlCon.setReadTimeout(30000);// 读取超时时间

		br = new BufferedReader(new InputStreamReader(urlCon.getInputStream(), code));// openStream()是为了获得一个inputstream
		String html = "";
		while ((html = br.readLine()) != null) {
			data += html + "\r\n";
		}
		br.close();
		return data;

	}

	public static String getLocalHost() {
		try {
			String osname = System.getProperty("os.name").toLowerCase();
			String host = "";
			if (osname.indexOf("win") >= 0) {
				host = InetAddress.getLocalHost().getHostAddress();
				;
			}
			if (osname.indexOf("linux") >= 0 || osname.indexOf("unix") >= 0) {
				host = getLocalIP();

			}
			return host;
		} catch (java.net.UnknownHostException e) {
			return "";
		}

	}

	public static String getLocalIP() {
		String ip = "";
		try {
			Enumeration<?> e1 = (Enumeration<?>) NetworkInterface
					.getNetworkInterfaces();
			while (e1.hasMoreElements()) {
				NetworkInterface ni = (NetworkInterface) e1.nextElement();
				if (!ni.getName().equals("eth0")) {
					continue;
				} else {
					Enumeration<?> e2 = ni.getInetAddresses();
					while (e2.hasMoreElements()) {
						InetAddress ia = (InetAddress) e2.nextElement();
						if (ia instanceof Inet6Address)
							continue;
						ip = ia.getHostAddress();
					}
					break;
				}
			}
		} catch (SocketException e) {
			e.printStackTrace();
			System.exit(-1);
		}
		return ip;
	}

	/* 一个将字节转化为十六进制ASSIC码的函数 */
	public static String byteHEX(byte ib) {
		char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a',
				'b', 'c', 'd', 'e', 'f' };
		char[] ob = new char[2];
		ob[0] = Digit[(ib >>> 4) & 0X0F];
		ob[1] = Digit[ib & 0X0F];
		String s = new String(ob);
		return s;
	}

	public static boolean checkUrl(String urlstr) {
		try {

			StringBuffer ret = new StringBuffer();
			String str;
			URL url = new URL(urlstr);
			BufferedReader br = new BufferedReader(new InputStreamReader(url
					.openStream()));
			String html = "";
			int count = 0;
			str = "";
			while ((html = br.readLine()) != null) {
				str = str + html.toString();
				if (++count >= 3)
					break;
			}
			str = str.trim();
			// System.out.println(str);
			br.close();
			if (!str.equals("")) {
				return true;
			}
		} catch (Exception ex) {
			System.out.println(ex);
		}
		return false;
	}

	public static String postHttp(String url, Map<String, String> params) {

		URL u = null;
		HttpURLConnection con = null;
		// 构建请求参数
		StringBuffer sb = new StringBuffer();
		if (params != null) {
			for (Entry<String, String> e : params.entrySet()) {
				sb.append(e.getKey());
				sb.append("=");
				sb.append(e.getValue());
				sb.append("&");
			}
			sb.substring(0, sb.length() - 1);
		}
		// System.out.println("send_url:"+url);
		// System.out.println("send_data:"+sb.toString());
		// 尝试发送请求
		try {
			u = new URL(url);
			con = (HttpURLConnection) u.openConnection();
			con.setConnectTimeout(10000);	// 连接超时时间
			con.setReadTimeout(30000);// 读取超时时间
			con.setRequestMethod("POST");
			con.setDoOutput(true);
			con.setDoInput(true);
			con.setUseCaches(false);
			con.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			OutputStreamWriter osw = new OutputStreamWriter(con
					.getOutputStream(), "UTF-8");

			osw.write(sb.toString());
			osw.flush();
			osw.close();

		} catch (Exception e) {

			e.printStackTrace();

		} finally {

			if (con != null) {

				con.disconnect();

			}

		}

		// 读取返回内容

		StringBuffer buffer = new StringBuffer();

		try {

			BufferedReader br = new BufferedReader(new InputStreamReader(con

			.getInputStream(), "UTF-8"));

			String temp;

			while ((temp = br.readLine()) != null) {

				buffer.append(temp);

				buffer.append("\n");

			}

		} catch (Exception e) {

			e.printStackTrace();

		}
		System.out.println(buffer.toString());
		return buffer.toString();

	}

	public static void main2(String[] args) throws Exception {
		String str = HttpUtil
				.getURL("http://localhost:8001/mobile/getPagePath.jsp?jspPath=visitList.jsp%3FpageIndex%3D0%26orderName%3Dorder%252520by%252520s.visitDate%252520desc%26showResultCount%3D1%26selectStr%3Ds.id%25252Cs.name%25252Cs.createDate%25252Cs.codeDate%25252Cs.codeNum%25252Cs.visitType%26pageCount%3D20%26prename%3Dvisit&htmlPath=visitList.html");
		System.out.println(str);
	}

	public static void downloadFile(String path, String url) throws Exception {
		// 创建文件对象
		File f = new File(path);
		downloadFile(f,url);
	}
	public static void downloadFile(File f, String url) throws Exception {
		log.info("start downlong file, path:{}, url:{}", new Object[]{f.getAbsolutePath(), url});
		URL urlfile = null;
		HttpURLConnection httpUrl = null;
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			urlfile = new URL(url);
			httpUrl = (HttpURLConnection) urlfile.openConnection();
			httpUrl.setConnectTimeout(10000);	// 连接超时时间
			httpUrl.setReadTimeout(30000);// 读取超时时间
			httpUrl.connect();
			
			// 创建文件路径
			if (!f.getParentFile().exists())
				f.getParentFile().mkdirs();
			
			bis = new BufferedInputStream(httpUrl.getInputStream());
			bos = new BufferedOutputStream(new FileOutputStream(f));
			int len = 2048;
			byte[] b = new byte[len];
			while ((len = bis.read(b)) != -1) {
				bos.write(b, 0, len);
			}
			bos.flush();
			bis.close();
			httpUrl.disconnect();
		} catch (Exception e) {
			log.error("download file error, path:"+ f.getAbsolutePath() +", url:" + url, e);
			throw new Exception(e);
		} finally {
			try {
				bis.close();
				bos.close();
			} catch (IOException e) {
				log.error("close file error", e);
			}
		}
	}

	public static void main(String[] args) throws Exception {
		String path = "d:/test.jpg";
		String url = "http://a.hiphotos.baidu.com/zhidao/pic/item/d4628535e5dde71148fdc772a7efce1b9d166103.jpg";
		HttpUtil.downloadFile(path, url);
	}

}
